package com.my.hotel.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.my.hotel.entity.serverPage.JdUser;
import com.my.hotel.service.ClientService;
import com.my.hotel.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/client")
public class ClientController {
    @Autowired
    private ClientService clientService;
    @RequestMapping("/clientPage")
    public String getPage(Model model, Integer pageNo){
        if(pageNo==null){
            pageNo=1;
        }
        PageHelper.startPage(pageNo,6);
        List<JdUser> list = clientService.getList();
        PageInfo<JdUser> page = new PageInfo<JdUser>(list);
        model.addAttribute("page",page);
        return "clientPage";
    }
    @RequestMapping("/clientAddPre")
    public String clientAddPre(){
        return "clientAdd";
    }

    @RequestMapping("/clientAdd")
    public String clientAdd(JdUser client,Model model){

        clientService.addClient(client);
        return getPage(model);
    }

    @RequestMapping("/deleteClient")
    public String deleteClient(int delId,Model model){
        clientService.delClient(delId);
        return getPage(model);
    }

    @RequestMapping("/clientPreUpdate")
    public String PreUpdate(int id,Model model){
        JdUser client=clientService.getClientById(id);
        model.addAttribute("client",client);
        return "clientUpdate";
    }

    @RequestMapping("/clientUpdate")
    public String clientUpdate(JdUser client,Model model){
        System.out.println(client);
        clientService.clientUpdate(client);
        return getPage(model);
    }

    @RequestMapping("/checkUsername")
    public void checkUsername(String username, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("utf-8");
        System.out.println(username);
        String result=clientService.checkUsername(username)?"true":"false";
        resp.getWriter().write(result);
    }

    //图片上传
    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(MultipartFile file) throws IOException {
        UUID uuid = UUID.randomUUID();
        InputStream is = file.getInputStream();
        Map<String, Object> map = OssUtil.upload(is, uuid.toString());
        System.out.println(map);
        String s = JSON.toJSONString(map);
        return s;
    }
    public String getPage(Model model){
        return getPage(model,1);
    }
}
